package com.guoji.cameracall.socket

import android.util.Log
import org.java_websocket.WebSocket
import org.java_websocket.client.WebSocketClient
import org.java_websocket.handshake.ClientHandshake
import org.java_websocket.handshake.ServerHandshake
import org.java_websocket.server.WebSocketServer
import java.lang.Exception
import java.net.InetSocketAddress
import java.net.URI
import java.nio.ByteBuffer

/**
 * create by zhongZihao on 2021/9/27
 */
class SocketLiveClient(private val uri: URI) : ISocketLive {
    private var myWebSocketClient: MyWebSocketClient? = null

    private var socketCallback: ((ByteArray?) -> Unit)? = null

    override fun start() {
        try {
            myWebSocketClient = MyWebSocketClient(uri)
            myWebSocketClient!!.connect()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun setDataCallback(socketCallback: (ByteArray?) -> Unit){
        this.socketCallback = socketCallback
    }

    override fun sendData(byteArray: ByteArray) {
        if (myWebSocketClient?.isOpen == true) {
            myWebSocketClient!!.send(byteArray)
        }
    }

    override fun close() {
        try {
            myWebSocketClient?.close()
            myWebSocketClient = null
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    inner class MyWebSocketClient(private val serverUri: URI) : WebSocketClient(serverUri) {
        override fun onOpen(handshakedata: ServerHandshake?) {
            Log.d("TAG_SocketLive", "SocketClient open ....$serverUri")
        }

        override fun onMessage(message: String?) {
        }

        override fun onMessage(buf: ByteBuffer) {
            val bytes = ByteArray(buf.remaining())
            buf.get(bytes)
            socketCallback?.invoke(bytes)
        }

        override fun onClose(code: Int, reason: String?, remote: Boolean) {
            Log.d("TAG_SocketLive", "SocketClient open ....")
        }

        override fun onError(ex: Exception?) {
        }
    }
}